﻿using LeSoft.Application.Bussiness;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LeSoft.Util;
using LeSoft.Application.Entity;
using LeSoft.Application.Code;
using System.Data;
using LeSoft.Application.Cache;
using System.IO;
using System.Collections;

namespace LeSoft.Application.Web.Areas.PropertyManage.Controllers
{
    public class CS_ComplaintsController : MvcControllerBase
    {
        private ComplaintsBLL cbll = new ComplaintsBLL();
        private static HttpFileCollection hfc;
        private static ArrayList hpf;

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit)]
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit)]
        public ActionResult Form()
        {
            hpf = new ArrayList();
            ViewBag.Mode = new CodeRuleBLL().CheckBillCodeMode(((int)CodeRuleEnum.ComplainCode).ToString());
            return View();
        }
        #region 单据状态树
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取树", "GetList")]
        private List<TreeStatusEntity> GetList(string queryJson)
        {
            DataTable dt = cbll.GetCountList(queryJson);
            List<TreeStatusEntity> li = new List<TreeStatusEntity>();
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (dt.Columns[i].ColumnName == "all")
                        li.Add(new TreeStatusEntity("0", EnumAttribute.GetDescription(TStateEnum.All), TStateEnum.All.ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "unhanding")
                        li.Add(new TreeStatusEntity(TStateEnum.All.ToString(), EnumAttribute.GetDescription(TStateEnum.UnHanding), ((int)TStateEnum.UnHanding).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "wating")
                        li.Add(new TreeStatusEntity(TStateEnum.All.ToString(), EnumAttribute.GetDescription(TStateEnum.Wating), ((int)TStateEnum.Wating).ToString(), dt.Rows[0][i].ToInt()));

                    else if (dt.Columns[i].ColumnName == "unprojected")
                        li.Add(new TreeStatusEntity(TStateEnum.All.ToString(), EnumAttribute.GetDescription(TStateEnum.UnProjected), ((int)TStateEnum.UnProjected).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "phanding")
                        li.Add(new TreeStatusEntity(((int)TStateEnum.UnProjected).ToString(), EnumAttribute.GetDescription(TStateEnum.PHanding), ((int)TStateEnum.PHanding).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "pcompleted")
                        li.Add(new TreeStatusEntity(((int)TStateEnum.UnProjected).ToString(), EnumAttribute.GetDescription(TStateEnum.PCompleted), ((int)TStateEnum.PCompleted).ToString(), dt.Rows[0][i].ToInt()));

                    else if (dt.Columns[i].ColumnName == "projected")
                        li.Add(new TreeStatusEntity(TStateEnum.All.ToString(), EnumAttribute.GetDescription(TStateEnum.Projected), ((int)TStateEnum.Projected).ToString(), dt.Rows[0][i].ToInt()));

                    else if (dt.Columns[i].ColumnName == "unsending")
                        li.Add(new TreeStatusEntity(((int)TStateEnum.Projected).ToString(), EnumAttribute.GetDescription(TStateEnum.UnSending), ((int)TStateEnum.UnSending).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "sending")
                        li.Add(new TreeStatusEntity(((int)TStateEnum.Projected).ToString(), EnumAttribute.GetDescription(TStateEnum.Sending), ((int)TStateEnum.Sending).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "handing")
                        li.Add(new TreeStatusEntity(((int)TStateEnum.Projected).ToString(), EnumAttribute.GetDescription(TStateEnum.Handing), ((int)TStateEnum.Handing).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "completed")
                        li.Add(new TreeStatusEntity(((int)TStateEnum.Projected).ToString(), EnumAttribute.GetDescription(TStateEnum.Completed), ((int)TStateEnum.Completed).ToString(), dt.Rows[0][i].ToInt()));

                    else if (dt.Columns[i].ColumnName == "unreturnback")
                        li.Add(new TreeStatusEntity(((int)TStateEnum.Completed).ToString(), EnumAttribute.GetDescription(TStateEnum.UnReturnBack), ((int)TStateEnum.UnReturnBack).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "returned")
                        li.Add(new TreeStatusEntity(((int)TStateEnum.Completed).ToString(), EnumAttribute.GetDescription(TStateEnum.Returned), ((int)TStateEnum.Returned).ToString(), dt.Rows[0][i].ToInt()));

                    else if (dt.Columns[i].ColumnName == "nothand")
                        li.Add(new TreeStatusEntity(TStateEnum.All.ToString(), EnumAttribute.GetDescription(TStateEnum.NotHand), ((int)TStateEnum.NotHand).ToString(), dt.Rows[0][i].ToInt()));

                    else
                        continue;
                }
            }
            return li;
        }

        /// <summary>
        /// 获取单据状态树
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取树", "GetStateTreeList")]
        public ActionResult GetStateTreeList(string queryJson)
        {
            var data = GetList(queryJson);
            List<TreeEntity> treeList = new List<TreeEntity>();
            foreach (TreeStatusEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.PValue == item.Value) == 0 ? false : true;
                tree.id = item.Value;
                tree.text = item.Text + "(" + item.Count + ")";
                tree.value = item.Value;
                if (item.PValue == "0") tree.isexpand = true;
                else tree.isexpand = false;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.parentId = item.PValue;
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }
        #endregion
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取列表数据", "GetPageListJson")]
        public ActionResult GetPageListJson(Pagination pagination, string queryJson)
        {
            var watch = CommonHelper.TimerStart();
            var data = cbll.GetPageList(pagination, queryJson);
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetForm, "获取表单数据", "GetFormJson")]
        public ActionResult GetFormJson(string keyValue)
        {
            var data = cbll.GetEntity(keyValue);
            var data2 = cbll.GetDEntity(keyValue);
            string BillId = data.SourceType == 2 ? data.SourceId : keyValue;
            var file = new AttachFileBLL().GetList(BillId);
            var task = new SysTaskBLL().GetList().Where(t => t.SourceId == data.Id);
            var taskSend = task != null ? task.FirstOrDefault(t => t.Type == 2) : null;
            var Worker = new AccountBLL().GetEntityByAccount(OperatorProvider.Provider.Current().Account).SourceId;
            var IsSendWay = taskSend == null ? false : new TaskUserBLL().ValidateUser(taskSend.Id, Worker) ? true : false;
            var taskDispose = task != null ? task.FirstOrDefault(t => t.State < 3 && t.Type == 1) : null;
            var IsDispose = taskDispose == null ? false : new TaskUserBLL().ValidateUser(taskDispose.Id, Worker) ? true : false;
            var taskReturn = task != null ? task.FirstOrDefault(t => t.State < 3 && t.Type == 3) : null;
            var IsReturn = taskReturn == null ? false : new TaskUserBLL().ValidateUser(taskReturn.Id, Worker) ? true : false;
            var jsonData = new
            {
                data1 = data,
                data2 = data2,
                data3 = file,
                IsSendWay = IsSendWay,
                IsDispose = IsDispose,
                IsReturn = IsReturn
            };
            return Content(jsonData.ToJson());
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "保存投诉", "SaveForm")]
        public ActionResult SaveForm(ComplaintBillEntity complaintBillEntity, ComplaintBillDetailEntity complaintBillDetailEntity, string KeyValue, string IMG)
        {
            try
            {
                List<Object> lst = IMG.ToObject<List<Object>>();
                List<AttachFileEntity> listFile = new List<AttachFileEntity>();
                string URL = Request.Url.ToString().Replace(Request.RawUrl, "/P");
                string SRC = URL.Substring(0, URL.IndexOf("/P"));
                string imgPath = "/Resource/ComplaintBillFile" + OperatorProvider.Provider.Current().CustomerCode + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
                foreach (var item in lst)
                {
                    var queryParam = item.ToString().ToJObject();
                    string Name = queryParam["Name"].ToString();
                    AttachFileEntity AttachFileEntity = new AttachFileEntity();
                    AttachFileEntity.Create();
                    AttachFileEntity.Category = 4;
                    AttachFileEntity.Type = 41;
                    AttachFileEntity.TypeName = "投诉单附件";
                    AttachFileEntity.FileName = Name;
                    string FilePath = Server.MapPath(imgPath);
                    AttachFileEntity.FileUrl = FilePath.Replace(HttpRuntime.AppDomainAppPath, SRC + "/") + Name;
                    listFile.Add(AttachFileEntity);
                }

                cbll.SaveForm(KeyValue, complaintBillEntity, complaintBillDetailEntity, listFile);
                return Success("操作成功。");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }

        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Delete, "删除投诉", "RemoveForm")]
        public ActionResult RemoveForm(string keyValue)
        {
            cbll.RemoveForm(keyValue);
            return Success("删除成功。");
        }
        [HttpPost]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Other, "上传文件", "UploadFile")]
        public ActionResult UploadFile()
        {

            hfc = System.Web.HttpContext.Current.Request.Files;
            string imgPath = "/Resource/ComplaintBillFile" + OperatorProvider.Provider.Current().CustomerCode + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
            if (hfc != null && hfc.Count > 0)
            {
                for (int i = 0; i < hfc.Count; i++)
                {
                    string FilePath = Server.MapPath(imgPath);
                    if (!Directory.Exists(FilePath))
                    {
                        Directory.CreateDirectory(FilePath);
                    }
                    hfc[i].SaveAs(FilePath + hfc[i].FileName);
                }
            }
            return Success("操作成功。");

        }

    }
}
